<script lang="ts">
    import { getContext } from "svelte";
    import Loading from "../Common/Loading/Loading.svelte";
    import { useClassList } from "../utils/useClassList";
    import { useClickAnimating } from "../utils/useClickAnimating";
    import type { ButtonProps } from "./Button";
    import { ButtonGroupContextKey, type ButtonGroupContext } from "../ButtonGroup";

    const ctx: ButtonGroupContext = getContext(ButtonGroupContextKey);

    const props: ButtonProps = $props();

    const [animating, setAnimating] = useClickAnimating();
    const type = $derived.by(() => props.type || ctx?.type || "default");
    const size = $derived.by(() => props.size || ctx?.size || "default");
    const theme = $derived.by(() => props.theme || ctx?.theme || "solid");
    const shape = $derived.by(() => props.shape || "square");
    const iconAlign = $derived.by(() => props.iconAlign || "left");
    const disabled = $derived.by(() => props.disabled || ctx?.disabled || false);

    const classList = $derived.by(() =>
        useClassList(props, "cm-button", {
            [`cm-button-icon-${iconAlign}`]: true,
            "cm-click-animating": $animating,
            "cm-button-block": props.block,
            [`cm-button-${type}`]: type,
            [`cm-button-theme-${theme}`]: theme,
            [`cm-button-${size}`]: size,
            "cm-button-active": props.active,
            "cm-button-circle": shape === "circle",
            "cm-button-round": shape === "round",
            "cm-button-icon-only": !!props.icon && !props.children,
            "cm-button-empty": !props.icon && !props.children,
        }),
    );

    function handleClick(e: any) {
        if (disabled || props.loading) {
            return;
        }
        props.onclick?.(e);
    }
</script>

{#snippet renderIcon()}
    {#if props.loading}
        <Loading />
    {:else if props.icon}
        <span class="cm-button-icon">{@render props.icon()}</span>
    {/if}
{/snippet}

<button type="button" class={classList} style={props.style} title={props.title} {disabled} onmouseup={setAnimating} onclick={handleClick}>
    {#if iconAlign === "left"}
        {@render renderIcon()}
    {/if}
    {@render props.children?.()}
    {#if iconAlign === "right"}
        {@render renderIcon()}
    {/if}
</button>
